﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Browser;
using System.Windows.Messaging;

namespace FIFP.Report.Model
{
    public class InBrowserCloseHandler : ICloseHandler
    {    
        private const string ScriptableObjectName = "InBrowserCloseHandler";

        #region ICloseHandler Members

        public void Initialize()
        {   
            HtmlPage.RegisterScriptableObject(ScriptableObjectName, this);
            string pluginName = HtmlPage.Plugin.Parent.Id;

            HtmlPage.Window.Eval(string.Format(
                @"window.onbeforeunload = function () {{
            var slApp = document.getElementById('{0}').getElementsByTagName('object')[0];
            var result = slApp.Content.{1}.OnBeforeUnload();
            if(result != null && result.length > 0)
                return result;
            }}",
                pluginName, ScriptableObjectName)
                );
        }

        public string Message { get; set; }

        #endregion

        [ScriptableMember]
        public void OnBeforeUnload()
        {
            if (App.QueryStringId.ToLower() == "ec")
            {
                var localMessageECSender = new LocalMessageSender(App.EcReceiverName,
                                                                 LocalMessageSender.Global);
                localMessageECSender.SendAsync("test");
            }
            else
            {
                var localMessageMCSender = new LocalMessageSender(App.McReceiverName,
                                                                LocalMessageSender.Global);
                localMessageMCSender.SendAsync("mctest");
            }
        }

       
    }
}
